package server.tasks;

import java.util.ArrayList;
import java.util.Collection;
import server.Logger;
import server.NodeInfo;
import server.SqlHandler;

public class TransactionFixerTask implements Runnable {
	private boolean stopped;
	private Collection<FixListener> listners = new ArrayList<FixListener>();
	private Collection<NodeInfo> nodes;

	public TransactionFixerTask(Collection<NodeInfo> nodes) {
		this.nodes = nodes;
		this.stopped = false;
	}

	@Override
	public void run() {
		boolean fixed = false;
		try {
			while (isStopped() == false && fixed == false) {
				int nodesToFix = 0, nodesFixed = 0;

				for (NodeInfo node : nodes) {
					if (node.isUpdateFailed()) {
						nodesToFix++;
						if (SqlHandler.finishTransactions(node)) {
							nodesFixed++;
						}
					}
				}
				
				if(nodesToFix == nodesFixed) {
					fixed = true;		
					for(FixListener listener : listners)
						listener.nodesFixed();
					Logger.logEvent("Udalo zakonczyc sie wiszace transakcje na wszystkich wezlach", Logger.LOG_STATUS);
				} else {				
					Thread.sleep(1000);
				}
			}
		} catch (InterruptedException e) {
			for(FixListener listener : listners)
				listener.fixInterrupted();
		}
	}

	public void registerListener(FixListener listener) {
		this.listners.add(listener);
	}

	public void unregisterListener(FixListener listener) {
		this.listners.remove(listener);
	}	
	
	public void stop() {
		synchronized (this) {
			this.stopped = true;
		}
	}

	public boolean isStopped() {
		synchronized (this) {
			return stopped;
		}
	}
}
